<?php

namespace Modules\Wechat\Model\Util\Dao;

class Db
{

    /**
     * 获取所有字段及其值
     *
     * @param \Modules\Wechat\Model\Dao\Db\Abstraction $DaoDb
     * @param bool                                     $without_null
     * @param array                                    $except
     *
     * @return array
     */
    public static function getColumns($DaoDb, $without_null = true, array $except = [])
    {
        $vars = get_object_vars($DaoDb);
        if (!is_array($vars)) {
            return [];
        }
        $return = [];
        foreach ($vars as $name => $value) {
            if ($without_null && is_null($value)) {
                continue;
            }
            if (false === array_search($name, $except)) {
                $return[$name] = $value;
            }
        }
        return $return;
    }

    protected static $table_columns = [];

    /**
     * 是否有某个字段
     *
     * @param \Modules\Wechat\Model\Dao\Db\Abstraction $DaoDb
     * @param string                                   $name
     *
     * @return bool
     */
    public static function hasColumn($DaoDb, $name)
    {
        $table_name = $DaoDb->getTableName();
        if (!isset(static::$table_columns[$table_name])) {
            static::$table_columns[$table_name] = static::getColumns($DaoDb, false);
        }
        return array_key_exists($name, static::$table_columns[$table_name]);
    }

}